import React from 'react';
import PropTypes from 'prop-types';
import getArcList from '../../../request/get_arc_list';
import deleteArticle from '../../../request/delete_artilce';
import Pagination from '../../../components/pagination/index';
import MyArticleItem from './my_article_item';
import './index.scss';

class MyArticle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      articlesList: [],
      hasArcticle: true,
    }
    this.deleteArticle = this.deleteArticle.bind(this)
    this.changePage = this.changePage.bind(this)
  }
  componentDidMount() {
    this.getArticlesList()
  }

  getArticlesList() {
    const params = {
      page: this.state.page,
      per_page: this.props.perPage,
      author: this.props.userInfo.user_id,
    };
    getArcList(params).then((res) => {
      if (res.data.length) {
        this.setState({
          articlesList: res.data,
          totalCount: res.data[0].total_count,
        })
      } else {
        this.setState({
          hasArcticle: false,
        })
      }
    })
  }
  // 点击改变分页
  changePage(index) {
    this.setState({
      page: index,
      articlesList: [],
    }, () => this.getArticlesList())
  }
  deleteArticle(id) {
    if (window.confirm('确定要删除此文章吗')) {
      deleteArticle(id, {}).then(() => {
        this.getArticlesList();
      })
    }
  }
  render() {
    const isPagination = this.state.totalCount > this.props.perPage;
    return (
      <div className="my-article">
        {this.state.hasArcticle ?
          this.state.articlesList.length ? this.state.articlesList.map(item => (
            <MyArticleItem data={item} key={item.id} deleteArticle={this.deleteArticle} />
          ))
            :
          <div className="loading">
              加载中...
          </div>
          :
          <div className="none">
            你还没有发表任何文章...
          </div>
        }
        {isPagination ? <Pagination pageSize={this.props.perPage} current={this.state.page} total={this.state.totalCount} onChange={this.changePage} /> : ''}
      </div>
    )
  }
}
export default MyArticle;
MyArticle.propTypes = {
  userInfo: PropTypes.objectOf(Object),
  perPage: PropTypes.number,
}
